package com.iwhalecloud.bss.kite.cucc.service.custview;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.QryIOTOppoDockingSalesRsp;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewAttr;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewBaseVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.GroupUserInfoVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.IndustryCache;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;

import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;

/**
 * @ClassName : GetUserInfoTask
 * @Description : 集团用户信息
 * @Author : xie.zhengjun
 * @Date : 2021/2/3 10:42
 */
@Deprecated
public class GetUserInfoTask extends CustViewBaseTask {
    private final ZLogger LOGGER = ZLoggerFactory.getLogger(this.getClass(), KeyConsts.LOG_MODULE);

    public GetUserInfoTask(Object[] args) {
        super(args);
    }

    @Override
    public CustViewBaseVO call() throws Exception {
        Object[] args = getArgs();
        Map<String, Object> userDetail = (Map<String, Object>) args[0];
        CustViewVO custViewVO = (CustViewVO) args[1];
        GroupUserInfoVO groupUserInfoVO = new GroupUserInfoVO();
        custViewVO.setGroupUser(groupUserInfoVO);

        if (KiteMapUtils.isNotEmpty(userDetail)) {
            // 用户信息
            Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
            // 合同信息
            List<Map<String, Object>> userContractInfos = (List<Map<String, Object>>) userDetail
                .get("USER_CONTRACT_INFOS");
            // 订单属性
            List<Map<String, Object>> userItemInfos = (List<Map<String, Object>>) userDetail.get("USER_ITEM_INFOS");
            Map<String, Map<String, Object>> userItemInfoMap = null;
            if (KiteListUtils.isNotEmpty(userItemInfos)) {
                userItemInfoMap = userItemInfos.stream().collect(Collectors
                    .toMap(stringObjectMap -> KiteMapUtils.getString(stringObjectMap, "CRM_ATTR_CODE"),
                        stringObjectMap -> stringObjectMap, (a, b) -> b));
            }

            assembleGroupUserInfoVO(groupUserInfoVO, userInfo, userContractInfos, userItemInfoMap);
        }
        return groupUserInfoVO;
    }

    private void assembleGroupUserInfoVO(GroupUserInfoVO groupUserInfoVO, Map<String, Object> userInfo,
                                         List<Map<String, Object>> userContractInfos, Map<String, Map<String, Object>> userItemInfoMap) {

        IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        String custId = KiteMapUtils.getString(userInfo, "CUST_ID");

        // 1 集团用户名称 USER_NAME
        String userNameVal = KiteMapUtils.getString(userInfo, "USER_NAME");
        CustViewAttr userName = new CustViewAttr("userName", "集团用户名称", userNameVal, userNameVal);

        // 2 业务号码 SERIAL_NUMBER
        String serialNumberVal = KiteMapUtils.getString(userInfo, "SERIAL_NUMBER");
        CustViewAttr serialNumber = new CustViewAttr("serialNumber", "业务号码", serialNumberVal, serialNumberVal);

        // 3 用户归属地 PROVINCE_CODE EPARCHY_CODE CITY_CODE
        String provinceCode = KiteMapUtils.getString(userInfo, "PROVINCE_CODE");
        String eparchyCode = KiteMapUtils.getString(userInfo, "EPARCHY_CODE");
        String cityCode = KiteMapUtils.getString(userInfo, "CITY_CODE");
        String regionValDesc = String.join(SymbolConsts.HYPHEN, LocalAttrHelper.getRegionName(provinceCode),
            LocalAttrHelper.getRegionName(eparchyCode), LocalAttrHelper.getRegionName(cityCode));
        String regionVal = String.join(SymbolConsts.HYPHEN, provinceCode, eparchyCode, cityCode);
        CustViewAttr region = new CustViewAttr("region", "用户归属地", regionVal, regionValDesc);

        // 4 产品名称 GOODS_ID
        String goodsId = KiteMapUtils.getString(userInfo, "GOODS_ID");
        String prodNameDesc = Optional.ofNullable(OfferCache.get(goodsId)).map(Offer::getOfferName).orElse(goodsId);
        CustViewAttr prodName = new CustViewAttr("prodName", "产品名称", goodsId, prodNameDesc);

        // 5 集团用户状态
        String userStateCode = Optional.ofNullable(String.valueOf(userInfo.get("SERVICE_STATE_CODE"))).orElse("");
        String userStateCodeDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020012105", userStateCode))
            .map(AttrValue::getAttrValueName).orElse(userStateCode);
        CustViewAttr state = new CustViewAttr("state", "集团用户状态", userStateCode, userStateCodeDesc);

        // 6 商机 ORD10036 110WLW10109974有数据
        String nicheVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.BUSINESS);
        if (KiteStringUtils.isEmpty(nicheVal)) {
            nicheVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.BUSINESS_NEW);
        }
        List<QryIOTOppoDockingSalesRsp> iotoOppoList = new ArrayList<>();
        try {
            iotoOppoList = infServiceBus.queryIOTOppoDockingSales(custId);
        } catch (BssException e) {
            LOGGER.error(ErrorConsts.INF_INVOKE_ERROR.getErrorCode(), e, "");
        }
        String finalNicheVal = nicheVal;
        String nicheValDesc = iotoOppoList.stream().filter(
            qryIOTOppoDockingSalesRsp -> KiteStringUtils.isEqual(qryIOTOppoDockingSalesRsp.getOppoNumber(), finalNicheVal))
            .findAny().map(QryIOTOppoDockingSalesRsp::getOppoName).orElse(nicheVal);
        CustViewAttr niche = new CustViewAttr("niche", "商机", nicheVal, nicheValDesc);

        // 7 是否总部直签客户 ORD10129 USER_ITEM_INFOS-CON3015
        String isSignVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.IS_LEADER_SIGN_NEW);
        String isSignValDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020110806", isSignVal))
            .map(AttrValue::getAttrValueName).orElse(isSignVal);
        CustViewAttr isSign = new CustViewAttr("isSign", "是否总部直签客户", isSignVal, isSignValDesc);

        // 8 是否总部收费 ORD10125 USER_ITEM_INFOS-CON3014
        String isChargeVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.IS_LEADER_CHARGE_NEW);
        String isChargeValDesc = Optional.ofNullable(AttrValueCache.getAttrValue("202011110001", isChargeVal))
            .map(AttrValue::getAttrValueName).orElse(
                Optional.ofNullable(AttrValueCache.getAttrValue("2020110806", isChargeVal))
                    .map(AttrValue::getAttrValueName).orElse(isChargeVal));
        CustViewAttr isCharge = new CustViewAttr("isCharge", "是否总部收费", isChargeVal, isChargeValDesc);

        // 9 行业 USER_ITEM_INFOS.ORD10050 110WLW10109974有数据
        String industryVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.INDUSTRY);
        if (KiteStringUtils.isEmpty(industryVal)) {
            industryVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.INDUSTRY_NEW);
        }
        String industryValDesc = Optional.ofNullable(IndustryCache.getIndustryName(industryVal)).orElse(industryVal);
        CustViewAttr industry = new CustViewAttr("industry", "行业", industryVal, industryValDesc);

        // 10 产品线 USER_ITEM_INFOS.ORD10051 110WLW10109974有数据
        String lineVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.PRODUCT_LINE);
        if (KiteStringUtils.isEmpty(lineVal)) {
            lineVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.PRODUCT_LINE_NEW);
        }
        String lineValDesc = Optional.ofNullable(IndustryCache.getIndustryName(lineVal)).orElse(lineVal);
        CustViewAttr line = new CustViewAttr("line", "产品线", lineVal, lineValDesc);

        // 11 细分重点产品 USER_ITEM_INFOS.ORD10052 110WLW10109974有数据
        String detailProdVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.SEGMENT_KEY_PRODUCT);
        if (KiteStringUtils.isEmpty(detailProdVal)) {
            detailProdVal = getValueFromUserItemInfoMap(userItemInfoMap, LocalKeyConsts.SEGMENT_KEY_PRODUCT_NEW);
        }
        String detailProdValDesc = Optional.ofNullable(IndustryCache.getIndustryName(detailProdVal))
            .orElse(detailProdVal);
        CustViewAttr detailProd = new CustViewAttr("detailProd", "细分重点产品", detailProdVal, detailProdValDesc);

        //12 缴费周期 FEE_CYCLE 110SPW400047存在
        String feeCycleVal = KiteMapUtils.getString(userInfo, "FEE_CYCLE");
        String feeCycleValDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020111102", feeCycleVal))
            .map(AttrValue::getAttrValueName).orElse(feeCycleVal);
        CustViewAttr feeCycle = new CustViewAttr("feeCycle", "缴费周期", feeCycleVal, feeCycleValDesc);

        // 13 账务周期 ACCOUNT_CYCLE
        String accountCycleVal = KiteMapUtils.getString(userInfo, "ACCOUNT_CYCLE");
        String accountCycleDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020111103", accountCycleVal))
            .map(AttrValue::getAttrValueName).orElse(accountCycleVal);
        CustViewAttr accountCycle = new CustViewAttr("accountCycle", "账务周期", accountCycleVal, accountCycleDesc);

        // 14 计费周期 ORD10235
        String chargeCycleValue = Optional.ofNullable(String.valueOf(userInfo.get("CHARGE_CYCLE"))).orElse("");
        String chargeCycleValueDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020111104", chargeCycleValue))
            .map(AttrValue::getAttrValueName).orElse(chargeCycleValue);
        CustViewAttr chargeCycle = new CustViewAttr("chargeCycle", "计费周期", chargeCycleValue, chargeCycleValueDesc);

        // 15 付费类型 BILL_TYPE
        String billTypeVal = KiteMapUtils.getString(userInfo, "BILL_TYPE");
        AttrValue attrValue = AttrValueCache.getAttrValue("2020111101", billTypeVal);
        String billTypeValDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020111101", billTypeVal))
            .map(AttrValue::getAttrValueName).orElse(billTypeVal);
        CustViewAttr billType = new CustViewAttr("billType", "付费类型", billTypeVal, billTypeValDesc);

        // 16 开户时间 OPEN_DATE
        String openDateVal = KiteMapUtils.getString(userInfo, "OPEN_DATE");
        //格式化时间 2021-01-07 14:59:00
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String openDateValDesc = "";
        try {
            Date parse = sdf.parse(openDateVal);
            openDateValDesc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(parse);
        } catch (ParseException e) {
//            e.printStackTrace();
            LOGGER.error(ErrorConsts.INF_INVOKE_ERROR.getErrorCode(), e, "");
        }
        CustViewAttr openDate = new CustViewAttr("openDate", "开户时间", openDateVal,
            KiteStringUtils.isEmpty(openDateValDesc) ? openDateVal : openDateValDesc);

        // 17 注销时间
        ProdInstQryDTO prodInstQryDTO = getProdInstQryDTO(custId, serialNumberVal, provinceCode, eparchyCode);
        String cancelDateVal = "";
        if (Objects.nonNull(prodInstQryDTO)) {
            cancelDateVal = prodInstQryDTO.getDistroy_time();
        }
        CustViewAttr cancelDate = new CustViewAttr("cancelDate", "注销时间", cancelDateVal, cancelDateVal);

        // 18 建档员工 IN_STAFF_ID
        String inStaffId = KiteMapUtils.getString(userInfo, "IN_STAFF_ID");
        String staffName = inStaffId;
        if (Objects.nonNull(prodInstQryDTO)) {
            staffName = prodInstQryDTO.getIn_staff_name();
        }
        CustViewAttr inStaff = new CustViewAttr("inStaff", "建档员工", inStaffId, staffName);

        // 19 建档渠道 IN_DEPART_ID 110SPW400047存在
        String inDepartId = KiteMapUtils.getString(userInfo, "IN_DEPART_ID");
        String inDepartName = inDepartId;
        if (Objects.nonNull(prodInstQryDTO)) {
            inDepartName = prodInstQryDTO.getIn_depart_name();
        }
        CustViewAttr inDepart = new CustViewAttr("inDepart", "建档渠道", inDepartId, inDepartName);

        // 20 合同 USER_CONTRACT_INFOS[0].CONTRACT_ID
        String contractId = "";
        if (KiteListUtils.isNotEmpty(userContractInfos)) {
            Map<String, Object> userContractInfo = userContractInfos.get(0);
            contractId = KiteMapUtils.getString(userContractInfo, "CONTRACT_ID");
        }
        CustViewAttr contract = new CustViewAttr("contract", "合同", contractId, "详情");

        groupUserInfoVO.setContractId(contractId);
        groupUserInfoVO.setCustId(custId);
        groupUserInfoVO.setProvinceCode(provinceCode);
        groupUserInfoVO.setAttrs(Lists
            .newArrayList(userName, serialNumber, region, prodName, state, niche, isSign, isCharge, industry, line,
                detailProd, feeCycle, accountCycle, chargeCycle, billType, openDate, cancelDate, inStaff, inDepart,
                contract));
    }

    /**
     * 查询某个用户的用户列表信息
     *
     * @param custId
     * @param serialNumberVal
     * @param provinceCode
     * @param eparchyCode
     * @return
     */
    private ProdInstQryDTO getProdInstQryDTO(String custId, String serialNumberVal, String provinceCode,
                                             String eparchyCode) {
        IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        ProdInstQryDTO prodInstQryDTO = null;
        Map<String, String> map = new HashMap<>(5);
        map.put("custId", custId);
        map.put("accNum", serialNumberVal);
        map.put("eparchyCode", eparchyCode);
        map.put("provinceCode", provinceCode);
        UserQueryDTO userQueryDTO = infServiceBus.queryUserList(map);
        if (Objects.nonNull(userQueryDTO)) {
            List<ProdInstQryDTO> userList = userQueryDTO.getUserList().getList();
            if (KiteListUtils.isNotEmpty(userList)) {
                prodInstQryDTO = userList.get(0);
            }
        }
        return prodInstQryDTO;
    }

    private String getValueFromUserItemInfoMap(Map<String, Map<String, Object>> userItemInfoMap, String attrField) {
        if (KiteMapUtils.isNotEmpty(userItemInfoMap)) {
            Map<String, Object> attrMap = userItemInfoMap.get(attrField);
            return KiteMapUtils.getString(attrMap, "ATTR_VALUE");
        }
        return "";
    }
}
